package com.ldl.origami.common;

import com.ldl.origami.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* @ClassName: SystemInterceptor
* @Description: 验证登录状态
* @author LDL
* @date 2014年4月18日 下午4:16:15
*
 */
public class SystemInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(SystemInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		String urlString = request.getRequestURL().toString();
        String userName = "";
		logger.debug("当前的URL为: " + urlString);
        HttpSession session = request.getSession();
		if(session!=null){

			if(session.getAttribute(Constants.SESSION_USERNAME)!=null){
				return true;
			}else{
                Cookie[] cookies = request.getCookies();
                if(cookies != null){
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("userName")) {
                            userName = cookie.getValue();
                            break;
                        }
                    }
                }
                if(userName.equals("")){
                    //如果访问主页则放行
                    if(urlString.contains("index")||urlString.contains("viewTheContents")){
                        return true;
                    }else{
                        request.getRequestDispatcher("/loginIndex").forward(request, response);
                        return false;
                    }
                }else{
                    session.setAttribute(Constants.SESSION_USERNAME,userName);
                    return true;
                }
			}
		}else{
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("userName")) {
                        userName = cookie.getValue();
                        break;
                    }
                }
            }

            if (userName.equals("")) {
                //如果访问主页则放行
                if (urlString.contains("index") || urlString.contains("viewTheContents")) {
                    return true;
                } else {
                    request.getRequestDispatcher("/loginIndex").forward(request, response);
                    return false;
                }
            } else {
                session.setAttribute(Constants.SESSION_USERNAME, userName);
                return true;
            }
		}
	}

}
